package com.jiuwei.mylibrary.basefragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * 基础Fragment类，提供ViewBinding支持
 * @param VB ViewBinding类型
 */
abstract class BaseFragment<VB : ViewBinding> : Fragment() {

    // ViewBinding实例
    protected lateinit var binding: VB

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 初始化ViewBinding
        binding = inflateBinding(inflater, container)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 初始化视图
        initView()
        // 初始化数据
        initData()
    }

    /**
     * 初始化ViewBinding
     */
    @Suppress("UNCHECKED_CAST")
    private fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): VB {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val clazz = type.actualTypeArguments[0] as Class<VB>
            val method = clazz.getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)
            return method.invoke(null, inflater, container, false) as VB
        } else {
            throw IllegalArgumentException("泛型参数错误")
        }
    }

    /**
     * 初始化视图，子类实现
     */
    protected abstract fun initView()

    /**
     * 初始化数据，子类可选实现
     */
    protected open fun initData() {}
}